<template>
	<view class="mine-info">
		<view class="top-nav">
			<view @click="backBtn">返回</view>
			<view>补录任务</view>
			<view></view>
		</view>
		<view class="main">
			<view class="main-item">
				<text>时间: </text>
				<uni-datetime-picker v-model="participationTime" style="width: 80%"/>
			</view>
			<view class="main-item">
				
				<text >地点:</text>
				
				<input v-model="address" style="width: 80%"/>
			</view>
			
			<view class="main-item" style="justify-content: left;">
				<text>任务描述:</text>
				<textarea style=" font: initial;" value="" placeholder="" maxlength="50" v-model="material" />
			</view>
			
			<view class="main-item">
				<text >场次:</text>
				<input style="width: 80%" maxlength="2" v-model="sessionsNum" type="number" />
			</view>
			<view class="main-item" style="flex-direction: column; justify-content: left;">
				<text >任务照片:</text>
				<view class="task-img">
					<view class="add-box" @tap="addPic">+</view>
					<view class="uni-upload-img uni-flex uni-row">
						<view class="flex-item preview_img" v-for="(image,index) in imageList" :key="index">
							<image class="uni-uploader__img" :src="image" :data-src="image" @tap="previewImage"></image>
							<view class="img_icon" @tap="delect(index)">x</view>
						</view>
					</view>
					
				</view>
			</view>
			<view class="main-item">
				<text>证明人:</text>
				<input style="width: 75%" type="text" maxlength="18" οninput="value= value.replace(/[^\d|xX]/g,'')" v-model="witness" />
			</view>
			<view class="main-item">
				<text>证明人手机:</text>
				<input style="width: 68%" type="text" maxlength="20" v-model="witnessPhone" />
			</view>
			<view class="attention">
				<text>注意：</text>
				<text>1、请核实信息的时效与准确</text>
				<text>2、有最新消息请及时反馈</text>
				<text>3、信息不全，影响证书发放</text>
			</view>
			
			<button class="sure" @click="submit()">确定</button>
		</view>
	</view>
</template>

<script>
var sourceType = [
            ['camera'],
            ['album'],
            ['camera', 'album']
        ]
    var sizeType = [
        ['compressed'],
        ['original'],
        ['compressed', 'original']
    ]
	import uFilePicker from "../../components/uni-file-picker_0.2.9/components/uni-file-picker/uni-file-picker.vue"
	
	import moment from "moment";
	
	var _this;
	export default {
		data() {
			return {
				baseUrl: 'http://weixiaokong.91xiaokong.com/jeecg-boot/',
				// baseUrl: 'http://192.168.3.30:8085/jeecg-boot/',
				// baseUrl: 'http://ey6pxx.natappfree.cc/jeecg-boot/',
				address: "",
				groupId: '',
				material:"",
				taskPic:"",
				participationTime: "",
				witnessPhone:"",
				witness:"",
				sessionsNum:"",
				id: "",
				idCard: "",
				openid: "",
				phone: "",
				remark: "",
				sex: "",
				techology: "",
				username: "",
				cityList: '',
				address:'',
				url: '',
				index: 0,
				nickname:"",
				headimgurl:"",
				groupName:'请选择',
				imageValue:[],



				// 上传图片
				imageList: [],
                sourceTypeIndex: 2,
                sourceType: ['拍照', '相册', '拍照或相册'],
                sizeTypeIndex: 2,
                sizeType: ['压缩', '原图', '压缩或原图'],
                countIndex: 8,
                count: [1, 2, 3, 4, 5, 6, 7, 8, 9],
                imgAllUrl:[],
				aa:[],


				// 时间选择器
			}
		},
		components:{
			uFilePicker,
		},
		
		onLoad() {
			_this = this;
			
			let openid = uni.getStorageSync('openid')
			if (openid) {
				_this.openId = openid
			}
			// 城市列表
			// uni.request({
			// 	url: _this.baseUrl + "api/rescue/queryGroup",
			// 	data: {
			// 		openid: _this.openId
			// 	},
			// 	success(res) {
			// 		_this.cityList = res.data.result;
			// 		if(!openid){
			// 			_this.groupId = res.data.result[0].id
			// 		}else{
			// 			// 用户回显
			// 			uni.request({
			// 				url: _this.baseUrl + "api/rescue/queryByOpenid",
			// 				data: {
			// 					openid: _this.openId
			// 				},
			// 				success(res) {
			// 					console.log(res);
			// 					if (res.data.code == 200) {
			// 						_this.address = res.data.result.address
			// 						_this.age = res.data.result.age
			// 						_this.company = res.data.result.company
			// 						_this.idCard = res.data.result.idCard
			// 						_this.phone = res.data.result.phone
			// 						_this.remark = res.data.result.remark
			// 						_this.sex = res.data.result.sex
			// 						_this.techology = res.data.result.techology
			// 						_this.username = res.data.result.username
			// 						_this.groupId = res.data.result.groupId
			// 						_this.id = res.data.result.id
			// 						console.log(document.getElementById('addRequestState').options.length)
			// 						let select = document.getElementById('addRequestState');
			// 						for(let i = 0;i < select.options.length;i++){
			// 							if(select[i].value == _this.groupId){
			// 								select.options[i].selected=true;
			// 							}
			// 						}
			// 					}
			// 				},
			// 				fail(err) {
			// 					console.log(err);
			// 				}
			// 			});
			// 		}
			// 	},
			// 	fail(err) {
			// 		console.log(err);
			// 	}
			// })
			
			_this.getopenId();
		},
		onShow() {
			
		},
		onReady() {

		},
		methods: {
			          
			
			// 返回按钮
			backBtn() {
				uni.navigateBack({
					delta: 1
				})
			},
			radioChange(e) {
				_this.sex = e.detail.value;
			},
			cityChange(e) {
				// console.log(_this.$refs.addRequestState.value);
				_this.address = _this.$refs.addRequestState.value;
			},
			submit() {
				
				
				if (
					_this.participationTime=="" ||
					_this.address=="" ||
					_this.material=="" ||
					_this.sessionsNum=="" ||
					
					_this.witness==""
				) {
					uni.showToast({
						title: "请认真填写信息",
						icon: "error"
					});
					return;
				}
				// if(_this.aa.length==0 ||
				// 	_this.aa.length>6){
				// 		uni.showToast({
				// 			title: "请上传1到6张照片",
				// 			icon:"none"
				// 		});
				// 		return;
				// 	}
				/* 验证手机号是否正确 */
				var reg_tel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
				if(!reg_tel.test(_this.witnessPhone)){
					uni.showToast({
						title: "请认真填写手机号",
						icon: "error"
					});  
					return false; 
				} 
				const openId = uni.getStorageSync('openid') || 'ogiDYs4eDr9DA2pofZeYsFQygtt4'
				uni.request({
					url: _this.baseUrl + "/rescue/hnjzRescueInformation/add",
					method: 'POST',
					header: {
						'Content-Type': 'application/json'
					},
					data: {
						participationTime: _this.participationTime,
						material:_this.material,
						sessionsNum:_this.sessionsNum,
						taskPic: _this.aa.join(','),
						witness: _this.witness,
						witnessPhone: +_this.witnessPhone,
						rescueType: 4,
						// idCard: _this.idCard,
						// phone: _this.phone,
						// remark: _this.remark,
						// sex: _this.sex,
						// techology: _this.techology,
						username: _this.username,
						address: _this.address,
						openId,
						id: _this.id
					},
					success(res) {
						console.log(res);
						if (res.data.code == 500) {
							alert(res.data.message)
						}
						if(res.data.code == 200){
							if(openId){
								alert('添加成功')
								uni.navigateBack({
									delta:1
								})
							}else{
								alert('添加成功')
								uni.navigateBack({
									delta:1
								})
								
							}
							
						}
					},
					fail(err) {
						console.log(err);
					}
				})
			},
			withData(param){
				return param < 10 ? '0' + param : '' + param;
			},
			change(e){
				let value = []
				e.detail.value.forEach((val,index) => {
					value.push(this.withData(val))
				})
				let dateArray = "20" + value[0] + "-" + value[1] + "-" + value[2] + " " + value[3] + ":" + value[4]
				this.upTower = dateArray
			},
			columnchange(e){
				let dateArr = this.dateTimeArray
				let arr = this.dateTime
				//滑动所在列的数据并对其值进行更新
				arr[e.detail.column] = e.detail.value
				//更新展示月份对应的天数（28 or 29 or 30 or 31）
				dateArr[2] = getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]])
				//最后把最新的数值赋值到dateTimeArray
				this.dateTimeArray = dateArr
				this.dateTime = arr
			},

			addPic : function(imgAll){
                this.imgAllUrl = [];
                let url = `${this.baseUrl}sys/common/app/upload `
                var that = this;
                uni.chooseImage({
                    sourceType: sourceType[this.sourceTypeIndex],
                    sizeType: sizeType[this.sizeTypeIndex],
                    count: this.imageList.length + this.count[this.countIndex] > 9 ? 9 - this.imageList.length :
                        this.count[this.countIndex],
                    success: (res) => {
                        this.imageList = this.imageList.concat(res.tempFilePaths);
                        var imageData = this.imageList
                        const tempFilePaths = res.tempFilePaths;
                        //上传个数循环拿到每一个照片的路径，然后放到一个数组中
                        for(var i=0;i<imageData.length;i++){
                            //图片上传
                            const uploadTask = uni.uploadFile({
                                url:url,
                                filePath: tempFilePaths[0],
								formData: {
									isup:1,
									bizPath: 'volunteer'  //剩下的字段
								}, 
                                name:"file",
                                success:function(data){
									console.log(data);
                                    const back = JSON.parse(data.data);
                                    var imgUrl = `https://shengrun.91xiaokong.com/chewei/${back.message}`;
                                    //将图片路径赋值给imgAllUrl
                                    that.imgAllUrl.push(imgUrl)
									that.aa.push(back.message);
                                }
                            })
                        }
                      },
                })
				console.log(this.imgAllUrl,'?????');
            },
            //图片预览
            previewImage: function(e) {
                var current = e.target.dataset.src
                uni.previewImage({
                    current: current,
                    urls: this.imageList
                })
            },
            delect(index,e){
                var that = this;
                uni.showModal({
                    title: '提示',
                    content: '是否删除该图片？',
                    success: (res) =>{
                        if (res.confirm) {
                            //删除数组中指定项
                            function removeByValue(arr, val) {
                                for(var i=0; i<arr.length; i++) {
                                    if(arr[i] == val) {
                                        arr.splice(i, 1);
                                        break;
                                    }
                                }
                            }
                            var forImg = that.imgAllUrl[index];
                            var imageUrl = that.imageList.splice(forImg, 1);

                            removeByValue(that.imageList, imageUrl);
                            const xx = that.aa;
							xx.splice(forImg, 1);
							that.aa = xx;
                            //重新赋值
                            that.imgAllUrl = that.imageList
                        } 
                    }
                });
            },
			// 获取openid
			getopenId() {
				let url = window.location.href;
				_this.url = url;
				let url_1 = url.split('?');
				if (url_1.length > 1) {
					let url_2 = url_1[1].split('&')
					url_2.forEach(function(e) {
						if (e.indexOf('openid') > -1) {
							_this.openId = e.split('=')[1];
							uni.setStorage({
								key: 'openid',
								data: _this.openId,
								success: function() {
									console.log('success');
								}
							});
						}
						if (e.indexOf('nickname') > -1) {
							_this.nickname = e.split('=')[1];
							uni.setStorage({
								key: 'nickname',
								data: _this.nickname,
								success: function() {
									console.log('success');
								}
							});
						}
						if (e.indexOf('headimgurl') > -1) {
							_this.headimgurl = e.split('=')[1];
							uni.setStorage({
								key: 'headimgurl',
								data: _this.headimgurl,
								success: function() {
									console.log('success');
								}
							});
						}
					})
				}
			},
		},
	}
</script>

<style>
	.attention{
		color: red;
		/* margin-left: 20rpx; */
		display: flex;
		flex-direction: column;
	}
	.task-img{
		display: flex;
	}
	.add-box{
		width: 119rpx;
		height: 119rpx;
		border: 1rpx #000 solid;
		font-size: 120rpx;
		text-align: center;
	}
	
	.task-img image{
		width: 120rpx;
		height: 120rpx;
	}
	.mine-info {

		padding-top: 100rpx;
	}

	.top-nav {
		line-height: 100rpx;
		display: flex;
		justify-content: space-between;
		background-color: #FFFFFF;
		margin-bottom: 20rpx;
		padding: 0 5%;
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		background-color: #FFFFFF;
		z-index: 1000;
	}

	.main {
		width: 90%;
		background-color: #FFFFFF;
		height: 1400rpx;
		border-radius: 40rpx;
		/* width: 98%; */
		margin: auto;
		box-shadow: 0px 0px 30px 0px rgba(0, 0, 0, 0.1);
	}

	.main-item {
		display: flex;
		justify-content: space-between;
		line-height: 100rpx;
		flex-wrap: wrap;
	}

	/* .main-item text {
		margin-left: 20rpx;
	} */

	.main-item input,.main-item .select {
		width: 70%;
		height: 60rpx;
		line-height: 60rpx;
		border: 2rpx solid #CCCCCC;
		border-radius: 30rpx;
		padding: 0 20rpx;
		margin: auto;
	}

	.main-item textarea {
		width: 100%;
		height: 180rpx;
		line-height: 200rpx;
		border: 2rpx solid #CCCCCC;
		border-radius: 30rpx;
		padding: 0 20rpx;
		margin: auto;
	}

	.sure {
		width: 80%;
		height: 80rpx;
		margin: 50rpx auto;
		border-radius: 50rpx;
		text-align: center;
		line-height: 80rpx;
		background-color: #b30002;
		color: #FFFFFF;
	}

	.radio {
		display: flex;
		width: 70%;
		margin: auto;
		padding: 0 20rpx;
	}

	.radio label {
		display: flex;
		margin-right: 20rpx;
	}

	.preview_img{
		position: relative;
		margin-left: 10px;
	}

	.uni-upload-img{
		display: flex;
	}

	.img_icon{
		background: rgba(0,0,0,.6);
		color: #fff;
		border-radius: 50%;
		position: absolute;
		right: -5px;
		top: -5px;
		display: inline-block;
		height: 20px;
		width: 20px;
		text-align: center;
		line-height: 20px;
	}
</style>
